const { redis } = require('../config')
const r = require('redis')

class Redis {
  constructor() {
    this.datas = {}
  }

  load(key, data) {
    this.datas[key] = data
    this.bind(key, data)
  }

  bind(key, data) {
    data.auth(redis.pwd, () => {
      console.log('redis: ' + key + '验证成功')
    })
    data.on('error', err => {
      console.error('redis: ' + key + '; 错误: ' + err)
    })
  }

  getData(key) {
    return this.datas[key]
  }

  set(dataKey, key, val, expire) {
    return new Promise(async (resolve, reject) => {
      let client = this.getData(dataKey)
      client.set(key, val, async () => {
        expire && (await this.expire(dataKey, key, expire))
        resolve()
      })
    })
  }

  get(dataKey, key) {
    return new Promise(async (resolve, reject) => {
      let client = this.getData(dataKey)
      await client.get(key, (err, res) => {
        if (err) reject(err)
        else resolve(res)
      })
    })
  }

  del(dataKey, key) {
    return new Promise(async (resolve, reject) => {
      let client = this.getData(dataKey)
      client.del(key, () => {
        resolve()
      })
    })
  }

  expire(dataKey, key, expire) {
    return new Promise(async (resolve, reject) => {
      let client = this.getData(dataKey)
      await client.expire(key, expire)
      resolve()
    })
  }
}

let data = new Redis()

const authCodeData = r.createClient({
  port: redis.port,
  host: redis.host,
  password: redis.pwd,
  db: 1
})
const contentData = r.createClient({
  port: redis.port,
  host: redis.host,
  password: redis.pwd,
  db: 2
})
data.load('authCode', authCodeData)
data.load('content', contentData)

module.exports = data